//============================================================================
// Name        : audiokck.cpp
// Author      : Tomasz Lipert
// Version     : 1.1
// Description :
//============================================================================

#include <iostream>
#include <SDL/SDL_audio.h>
#include <fftw3.h>
#include <cmath>
#include <SDL/SDL.h>
#include <SDL/SDL_draw.h>

using namespace std;

int WIDTH = 1200;
int HEIGHT = 600;

Uint32 colors[1024];

int main() {

	SDL_Surface *screen = NULL;
	SDL_Init(SDL_INIT_EVERYTHING);
	screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_SWSURFACE);

	SDL_AudioSpec wav_spec;
	Uint32 wav_length;
	Uint8 *wav_buffer;

	fftw_complex *in, *out;
	fftw_plan p;

	int N = 256;
	for (int i = 0; i < 256; i++) {
		colors[i] = SDL_MapRGB(screen->format, 0, i, 255);
		//colors[i] = SDL_MapRGB(screen->format, 255, i, 0);
	}

	for (int i = 0; i < 256; i++) {
		colors[256+i] = SDL_MapRGB(screen->format, 0, 255, 255-i);
		//colors[256 + i] = SDL_MapRGB(screen->format, 255 - i, 255, 0);
	}

	for (int i = 0; i < 256; i++) {
		colors[512+i] = SDL_MapRGB(screen->format, i, 255, 0);
		//colors[512 + i] = SDL_MapRGB(screen->format, 0, 255, i);
	}

	for (int i = 0; i < 256; i++) {
		colors[768+i] = SDL_MapRGB(screen->format, 255, 255-i, 0);
		//colors[768 + i] = SDL_MapRGB(screen->format, 0, 255 - i, 255);
	}

	/* open audio */
	if (SDL_LoadWAV("rosnacy1.wav", &wav_spec, &wav_buffer, &wav_length) == NULL) {
		fprintf(stderr, "Could not open test.wav: %s\n", SDL_GetError());
		exit(-1);
	}

	Sint16* samples = (Sint16*) (wav_buffer);

	//cout << "aaaaaaaaaaaaaaaaaaaaaaaaaa" << wav_length << endl;

	double* table = new double[256];
	double* result = new double[256];

	for (int j = 0; j < wav_length/512; j++) {
		for (int i = 0; i < 256; i++) {
			table[i] = samples[256*j+i];
		}

		in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
		out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
		p = fftw_plan_dft_r2c_1d(N, table, out, FFTW_ESTIMATE);

		fftw_execute(p);
		for (int i = 0; i < 256; i++) {
			result[i] = sqrt(out[i][0] * out[i][0] + out[i][1] * out[i][1]);
		}

		/*for (int i = 0; i < 256; i++) {
			cout << "result " << i << " " << result[i] << endl;
		}*/

		int max = 0;
		int min = 999999;
		for (int i = 0; i < 256; i++) {
			if (result[i] < min)
				min = result[i];
			if (result[i] > max)
				max = result[i];
		}

		//cout << max << " " << min << endl;
		int divider;
if(max > 1024) divider = max/1024;
else divider = 1024/max;
		for (int i = 0; i < 128; i++) {
			Draw_Pixel(screen, 10 + j, 138 - i,
					colors[(int) (result[i] / divider)]);
			///cout << (int)(result[i] / divider) << endl;
		}
	}

	SDL_Flip(screen);

	SDL_Delay(3000);
	SDL_Quit();
	fftw_destroy_plan(p);
	fftw_free(in);
	fftw_free(out);
	return 0;
}
